package com.hx_ai.nlp.simple.query;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.util.DateUtils;
import com.hx_ai.nlp.simple.utils.GaodeWeatherProperties;
import com.hx_ai.nlp.simple.utils.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;

import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class WeatherQuery extends AbstractQuery{

    private final GaodeWeatherProperties weatherProperties = new GaodeWeatherProperties();
    private final String query;      // 查询
    private String cityCode;
    private String keyDate;

    private static final String appKey = "72769f345c9d1094fbf7d665693aeb24";

    private static final String urlTemplate = "https://restapi.amap.com/v3/weather/weatherInfo?key={0}&city={1}&extensions=all";
    private static final String urlTemplate_2 = "https://restapi.amap.com/v3/weather/weatherInfo?key={0}&city={1}";

    public WeatherQuery(String query) {
        this.query = query;
    }

    private boolean existWeather(){
        Map<String, String> gaodeWeather = weatherProperties.getGaodeWeather();
        if (!ObjectUtils.isEmpty(gaodeWeather)){
            for (Map.Entry<String, String> x : gaodeWeather.entrySet()) {
                if (StringUtils.isNotBlank(x.getKey())){
                    if (StringUtils.contains(query, x.getKey())){
                        cityCode = x.getValue();
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public boolean existWeatherKeyword(){
        List<String> keyword = weatherProperties.getKeyword();
        if (!ObjectUtils.isEmpty(keyword)){
            for (String keywordi : keyword) {
                if (StringUtils.contains(query, keywordi)){
                    return true;
                }
            }
        }
        return false;
    }

    public boolean existDate(){
        Map<String, Long> dateToDay = weatherProperties.getDateToDay();
        for (Map.Entry<String, Long> x : dateToDay.entrySet()) {
            if (query.contains(x.getKey())) {
                Long value = x.getValue();
                Date date = new Date(value);
                keyDate = DateUtils.format(date, DateUtils.DateTimeFormatPattern.DATE_FORMAT_10_DASH.pattern);
                return true;
            }
        }
        return false;
    }

    @Override
    public String getResult() {
        String urlTemplateStr;
        if (StringUtils.isBlank(keyDate)){
            urlTemplateStr = urlTemplate_2;
        }else {
            urlTemplateStr = urlTemplate;
        }
        String url = MessageFormat.format(urlTemplateStr, appKey, cityCode);
        String html = HttpClientUtil.grabHtmlOnce(String.format(url));
        JSONObject jo = JSONObject.parseObject(html);
        return this.parseJson(jo, keyDate);
    }

    private String parseJson(JSONObject json, String keyDate){
        if (ObjectUtils.isEmpty(json)
                || !json.containsKey("status")
                || !StringUtils.equalsAny(json.getString("status"), "1")
                || !StringUtils.equalsAny(json.getString("infocode"), "10000")
                || !json.containsKey("forecasts")){
            return "暂时没有" + query + "的天气信息";
        }
        JSONArray forecasts = JSONObject.parseArray(JSONObject.toJSONString(json.get("forecasts")));
        if (ObjectUtils.isEmpty(forecasts)){
            return "暂时没有" + query + "的天气信息";
        }

        // 这里的天气数据可以考虑加缓存，同一个地方不需要每次都调用接口
        Map<String, String> weatherMap = new HashMap<>(16);
        StringBuilder weatherReportStr_1 = new StringBuilder();
        for (Object forecast : forecasts) {
            JSONObject forecastJSON = JSONObject.parseObject(JSONObject.toJSONString(forecast));
            String city;
            String reporttime;
            String casts;
            if (!forecastJSON.containsKey("city") ||
                    !forecastJSON.containsKey("reporttime") ||
                    !forecastJSON.containsKey("casts")){
                return "暂时没有" + query + "的天气信息";
            }
            reporttime = forecastJSON.getString("reporttime");
            city = forecastJSON.getString("city");
            casts = forecastJSON.getString("casts");
            weatherReportStr_1.append(city).append(reporttime).append("的天气预报").append("\n");

            JSONArray castsJSONArray = JSONObject.parseArray(casts);
            for (Object cast : castsJSONArray) {
                JSONObject dayJSON = JSON.parseObject(JSONObject.toJSONString(cast));
                String date = (String) dayJSON.get("date");
                if (ObjectUtils.isEmpty(date)) {
                    continue;
                }
                String week = (String) dayJSON.get("week");
                String dayweather = (String) dayJSON.get("dayweather");
                String nightweather = (String) dayJSON.get("nightweather");
                String daytemp = (String) dayJSON.get("daytemp");
                String nighttemp = (String) dayJSON.get("nighttemp");
                String daywind = (String) dayJSON.get("daywind");
                String nightwind = (String) dayJSON.get("nightwind");
                String daypower = (String) dayJSON.get("daypower");
                String nightpower = (String) dayJSON.get("nightpower");
                String weatherReportStr_2 = "日期:" + date + "," +
                        "星期:" + week + "," +
                        "白天天气现象:" + dayweather + "," +
                        "晚上天气现象:" + nightweather + "," +
                        "白天温度:" + daytemp + "," +
                        "晚上温度:" + nighttemp + "," +
                        "白天风向:" + daywind + "," +
                        "晚上风向:" + nightwind + "," +
                        "白天风力:" + daypower + "," +
                        "晚上风力:" + nightpower + "," + "\n";
                weatherMap.put(date, weatherReportStr_2);
            }
        }
        if (ObjectUtils.isNotEmpty(weatherMap)){
            for (Map.Entry<String, String> entry : weatherMap.entrySet()) {
                String date = entry.getKey();
                String weatherStr = entry.getValue();
                if (StringUtils.equalsAny(keyDate, date)){
                    return weatherReportStr_1.append(weatherStr).toString();
                }
            }
        }
        return "暂时没有" + query + "的天气信息";
    }

    public boolean isWeather() {
        boolean b1 = this.existWeatherKeyword();
        if (b1){
            boolean b2 = this.existDate();
            if (!b2){
                this.keyDate = DateUtils.format(new Date(), DateUtils.DateTimeFormatPattern.DATE_FORMAT_10_DASH.pattern);
            }
            return this.existWeather();
        }
        return false;
    }
}
